"""Package for allwpilib"""
import os
import shutil
from conans import ConanFile, tools
from conan.tools.cmake import CMake, CMakeToolchain, CMakeDeps
from conan.tools.layout import cmake_layout

class AllWpilibConan(ConanFile):
    """Package for allwpilib"""
    name = "allwpilib"

    # Optional metadata
    url = "https://github.com/conan-io/conan-center-index"
    license = "Wpilib"
    license_url = "https://github.com/wpilibsuite/allwpilib/blob/main/LICENSE.md"
    homepage = "https://github.com/wpilibsuite/allwpilib"
    description = "The core libraries for creating robot programs for the frc roboRIO"
    topics = ("frc", "robotics", "wpilib", "first")

    # Binary configuration
    settings = "os", "compiler", "build_type", "arch"
    exports_sources = "patches/**"
    options = {
        #"shared": [True, False],
        "with_gui": [True, False],
        "with_cscore": [True, False],
        "with_wpilib": [True, False],
        "with_wpimath": [True, False],
        "with_simulation_modules": [True, False]
    }
    default_options = {
        #"shared": False,
        "with_gui": True,
        "with_cscore": True,
        "with_wpilib": True,
        "with_wpimath": True,
        "with_simulation_modules": True
    }

    _cmake = None

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    #def config_options(self):
    #    """Modify configuration options depending on platform"""

    def requirements(self):
        """Pull wpilib requirements"""
        if self.options.with_cscore:
            self.requires("opencv/4.5.3")
        if self.options.with_wpimath:
            self.requires("eigen/3.4.0")
        if self.options.with_gui:
            self.requires("glfw/3.3.4")
            self.requires("glu/system")

    def source(self):
        if self.version == "latest":
            git = tools.Git(folder=".")
            git.clone("https://github.com/wpilibsuite/allwpilib", "main")
        else:
            tools.get(**self.conan_data["sources"][self.version], strip_root=True, destination=".")
        for patch in self.conan_data["patches"][self.version]:
            tools.patch(**patch)

    def generate(self):
        """Generate cmake toolchain and deps"""
        on_off = lambda v: "ON" if v else "OFF"
        toolchain = CMakeToolchain(self)
        toolchain.variables["WITH_GUI"]                = on_off(self.options.with_gui)
        toolchain.variables["WITH_JAVA"]               = "OFF"
        toolchain.variables["WITH_TESTS"]              = "OFF"
        toolchain.variables["WITH_CSCORE"]             = on_off(self.options.with_cscore)
        toolchain.variables["WITH_WPILIB"]             = on_off(self.options.with_wpilib)
        toolchain.variables["WITH_WPIMATH"]            = on_off(self.options.with_wpimath)
        toolchain.variables["WITH_SIMULATION_MODULES"] = on_off(self.options.with_simulation_modules)
        #if self.options.with_simulation_modules == True:
        toolchain.variables["WITH_SHARED_LIBS"]        = "ON"
        #else:
        #    toolchain.variables["WITH_SHARED_LIBS"] = str(on_off(self.options.shared))
        toolchain.generate()
        deps = CMakeDeps(self)
        deps.generate()

    def layout(self):
        """What's this for?"""
        cmake_layout(self)

    def build(self):
        """Call CMake build command"""
        _cmake = CMake(self)
        _cmake.configure()
        _cmake.build()

    def package(self):
        """Use CMake's built in install functionality to package outputs"""
        _cmake = CMake(self)
        _cmake.configure()
        _cmake.install()
        #self.copy(pattern="bin", src=self._build_subfolder, dst="bin")
        self.copy(pattern="LICENSE.md", src=".", dst="licenses")
        shutil.copytree(os.path.join(self.package_folder, "wpilib", "include"), os.path.join(self.package_folder, "include"))
        shutil.copytree(os.path.join(self.package_folder,"wpilib", "lib"), os.path.join(self.package_folder, "lib"))
        shutil.rmtree(os.path.join(self.package_folder, "share"))
        shutil.rmtree(os.path.join(self.package_folder, "wpilib"))

    def package_info(self):
        """Data about libraries within package"""
        self.cpp_info.names["cmake_find_package"] = self.name
        self.cpp_info.names["cmake_find_package_multi"] = self.name

        bin_path = os.path.join(self.package_folder, "bin")
        self.output.info("Appending PATH env var with : {}".format(bin_path))
        self.env_info.PATH.append(bin_path)

        libsufix = "d" if self.settings.build_type == "Debug" else ""

        if self.options.with_cscore:
            self.cpp_info.components["cscore"].includedirs = [
                "include/cscore",
                "include/cameraserver"
            ]
            self.cpp_info.components["cscore"].libdirs = ["lib"]
            self.cpp_info.components["cscore"].libs = [
                "cameraserver" + libsufix,
                "cscore" + libsufix
            ]

        if self.options.with_gui:
            self.cpp_info.components["wpigui"].includedirs = ["include/wpigui"]
            self.cpp_info.components["wpigui"].libdirs = ["lib"]
            self.cpp_info.components["wpigui"].libs = ["wpigui" + libsufix]
            self.cpp_info.components["glass"].includedirs = ["include/glass"]
            self.cpp_info.components["glass"].libdirs = ["lib"]
            self.cpp_info.components["glass"].libs = [
                "glass" + libsufix,
                "glassnt" + libsufix
            ]

        if self.options.with_simulation_modules:
            self.cpp_info.components["halsim"].includedirs = ["include/hal"]
            self.cpp_info.components["halsim"].libdirs = ["lib"]
            self.cpp_info.components["halsim"].libs = [
                "wpiHal" + libsufix,
                "halsim_ws_core" + libsufix,
                "halsim_ds_socket" + libsufix,
                "halsim_ws_client" + libsufix,
                "halsim_ws_server" + libsufix
            ]
            if self.options.with_gui:
                self.cpp_info.components["halsim"].libs.append("halsim_gui" + libsufix)

        if self.options.with_wpilib:
            self.cpp_info.components["wpilibc"].includedirs = [
                "include/wpilibc",
                "include/wpilibNewCommands"
            ]
            self.cpp_info.components["wpilibc"].libdirs = ["lib"]
            self.cpp_info.components["wpilibc"].libs = [
                "wpilibc" + libsufix,
                "wpilibNewCommands" + libsufix
            ]

        if self.options.with_wpimath:
            self.cpp_info.components["wpimath"].includedirs = ["include/wpimath"]
            self.cpp_info.components["wpimath"].libdirs = ["lib"]
            self.cpp_info.components["wpimath"].libs = ["wpimath" + libsufix]

        self.cpp_info.components["wpiutil"].includedirs = ["include/wpiutil"]
        self.cpp_info.components["wpiutil"].libdirs = ["lib"]
        self.cpp_info.components["wpiutil"].libs = ["wpiutil" + libsufix ]

        self.cpp_info.components["ntcore"].includedirs = ["include/ntcore"]
        self.cpp_info.components["ntcore"].libdirs = ["lib"]
        self.cpp_info.components["ntcore"].libs = ["ntcore" + libsufix]
